//
package com.seguriapp.activities;

import java.util.List;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.seguriapp.R;
import com.seguriapp.controllers.EntityController;
import com.seguriapp.dialogs.SelectCategoryDialog;
import com.seguriapp.entities.Entity;
import com.seguriapp.other.CategoryDialogInterface;

/**
 * TODO(pjohnson): Insert description
 * 
 * @author Pablo Johnson (pjohnson@avantica.net)
 */
public class EntityMapFragmentActivity extends FragmentActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_complaint_list);
		if (savedInstanceState == null) {
			// Do first time initialization -- add initial fragment.
			Fragment newFragment = EntityMapFragment.newInstance();
			FragmentTransaction ft = getSupportFragmentManager()
					.beginTransaction();
			ft.add(R.layout.fragment_entity_map, newFragment).commit();
		}
	}

	public static class EntityMapFragment extends Fragment
			implements
				CategoryDialogInterface {

		static EntityMapFragment newInstance() {
			final EntityMapFragment f = new EntityMapFragment();
			return f;
		}

		private GoogleMap mMap;

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			super.onCreateView(inflater, container, savedInstanceState);
			setHasOptionsMenu(true);
			return inflater.inflate(R.layout.fragment_entity_map, container,
					false);
		}

		public void onDestroyView() {
			super.onDestroyView();
			try {
				Fragment fragment = (getFragmentManager()
						.findFragmentById(R.id.map));
				if (fragment != null) {
					FragmentTransaction ft = getActivity()
							.getSupportFragmentManager().beginTransaction();
					ft.remove(fragment);
					ft.commit();
				}
			} catch (Exception e) {

			}
		}

		@Override
		public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
			inflater.inflate(R.menu.select_crime_categories, menu);
			super.onCreateOptionsMenu(menu, inflater);
		}

		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			switch (item.getItemId()) {
				case R.id.select_category_menu :
					final FragmentManager fm = getActivity()
							.getSupportFragmentManager();
					final SelectCategoryDialog categoryDialog = new SelectCategoryDialog(
							this, SelectCategoryDialog.ENTITY_CATEGORY);
					categoryDialog.show(fm, "category_dialog");
					break;
				default :
					break;
			}
			return super.onOptionsItemSelected(item);
		}

		@Override
		public void onResume() {
			mMap = ((SupportMapFragment) getActivity()
					.getSupportFragmentManager().findFragmentById(R.id.map))
					.getMap();
			mMap.setMyLocationEnabled(true);
			final LocationManager service = (LocationManager) getActivity()
					.getSystemService(LOCATION_SERVICE);
			final Criteria criteria = new Criteria();
			final String provider = service.getBestProvider(criteria, false);
			final Location location = service.getLastKnownLocation(provider);
			final LatLng userLocation = new LatLng(location.getLatitude(),
					location.getLongitude());
			mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation,
					13));
			onChangeCategories();
			super.onResume();
		}

		@Override
		public void onChangeCategories() {
			// comenzarDialogo();
			mMap.clear();
			obtenerEntidades();
		}

		private void obtenerEntidades() {
			new Thread(new Runnable() {
				public void run() {
					final LocationManager service = (LocationManager) getActivity()
							.getSystemService(LOCATION_SERVICE);
					final Criteria criteria = new Criteria();
					final String provider = service.getBestProvider(criteria,
							false);
					final Location location = service
							.getLastKnownLocation(provider);

					final EntityController eController = new EntityController(
							getActivity());
					final List<Entity> items = eController.getEntityListForMap(
							getActivity().getIntent().getStringExtra("typeId"),
							location.getLatitude(), location.getLongitude());
					getActivity().runOnUiThread(new Runnable() {

						@Override
						public void run() {
							if (items != null) {
								updateLocations(items);
							}
						}
					});
				}
			}).start();

		}

		public void updateLocations(List<Entity> items) {
			for (int i = 0; i < items.size(); i++) {
				final Entity entity = items.get(i);
				mMap.addMarker(new MarkerOptions()
						.position(
								new LatLng(entity.getLatitude(), entity
										.getLongitude()))
						.icon(BitmapDescriptorFactory
								.fromResource(R.drawable.police2))
						.title(entity.getNombre())
						.snippet(entity.getTelefono()));
			}
		}

	}

}
